package com.work.yshop.ui.activity;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.WindowCompat;

import com.bumptech.glide.Glide;
import com.work.yshop.R;
import com.work.yshop.databinding.ActivityProductDetailBinding;
import com.work.yshop.model.CartItem;
import com.work.yshop.model.Favorite;
import com.work.yshop.model.Order;
import com.work.yshop.model.Product;
import com.work.yshop.model.ProductDetail;
import com.work.yshop.model.ProductHistory;
import com.work.yshop.mvp.contract.UserDataContract;
import com.work.yshop.mvp.presenter.UserDataPresenter;
import com.work.yshop.provider.ProductProvider;
import com.work.yshop.utils.ImageLoader;
import com.work.yshop.utils.UserSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.text.SimpleDateFormat;

public class ProductDetailActivity extends AppCompatActivity implements UserDataContract.View {

    private static final int REQUEST_EDIT_PRODUCT = 100;

    private ActivityProductDetailBinding binding;
    private ProductDetail productDetail;
    private UserDataPresenter presenter;
    private boolean isFavorite = false;
    private long productId;
    private int cartCount = 0;

    private ImageView btnBack;
    private ImageView btnEdit;
    private ImageView ivProduct;
    private TextView tvProductName;
    private TextView tvPrice;
    private TextView tvStock;
    private TextView tvStatus;
    private TextView tvCategory;
    private TextView tvDescription;
    private TextView tvPublishDate;
    private TextView tvUpdateDate;
    private Button btnToggleStatus;
    private Button btnEditProduct;

    /**
     * 启动商品详情页面的静态方法
     * @param context 上下文
     * @param productId 商品ID
     */
    public static void start(Context context, long productId) {
        Intent intent = new Intent(context, ProductDetailActivity.class);
        intent.putExtra("product_id", productId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 设置状态栏透明，内容延伸到状态栏
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        
        // 使用ViewBinding
        binding = ActivityProductDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        // 初始化Presenter
        presenter = new UserDataPresenter(this);
        presenter.attachView(this);
        
        // 设置Toolbar
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("");
        
        // 获取传入的商品ID
        productId = getIntent().getLongExtra("product_id", -1);
        if (productId == -1) {
            Toast.makeText(this, "商品ID无效", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        initViews();
        setupListeners();
        loadProductDetail((int)productId);
        
        // 检查是否已收藏
        checkFavoriteStatus();
        
        // 加载购物车数量
        loadCartCount();
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        // 使用ViewBinding，不需要findViewById
        // 这里可以进行一些其他的视图初始化工作
    }
    
    /**
     * 设置监听器
     */
    private void setupListeners() {
        // 返回按钮
        binding.btnBack.setOnClickListener(v -> finish());
        
        // 分享按钮
        binding.btnShare.setOnClickListener(v -> {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, productDetail.getName());
            shareIntent.putExtra(Intent.EXTRA_TEXT, "我发现了一个好东西: " + productDetail.getName() + "，价格: ¥" + productDetail.getPrice());
            startActivity(Intent.createChooser(shareIntent, "分享商品"));
        });
        
        // 收藏按钮
        binding.btnFavorite.setOnClickListener(v -> toggleFavorite());
        
        // 客服按钮
        binding.btnCustomerService.setOnClickListener(v -> {
            Toast.makeText(this, "联系客服", Toast.LENGTH_SHORT).show();
            // 跳转到聊天页面
            Intent intent = new Intent(this, ChatActivity.class);
            intent.putExtra("shop_id", productDetail.getShopId());
            intent.putExtra("shop_name", productDetail.getShopName());
            startActivity(intent);
        });
        
        // 购物车按钮
        binding.btnCart.setOnClickListener(v -> {
            // 跳转到购物车页面
            Intent intent = new Intent(this, CartActivity.class);
            startActivity(intent);
        });
        
        // 进店逛逛按钮
        binding.btnEnterShop.setOnClickListener(v -> {
            Toast.makeText(this, "进入店铺: " + productDetail.getShopName(), Toast.LENGTH_SHORT).show();
            // 这里可以跳转到店铺页面
        });
        
        // 加入购物车按钮
        binding.btnAddToCart.setOnClickListener(v -> addToCart());
        
        // 立即购买按钮
        binding.btnBuyNow.setOnClickListener(v -> buyNow());
    }
    
    /**
     * 加载商品详情数据
     */
    private void loadProductDetail(int productId) {
        // 这里应该从网络或本地数据库加载商品详情
        // 这里先使用模拟数据
        productDetail = createMockProductDetail(productId);
        
        // 显示商品数据
        displayProductDetail();
        
        // 添加到浏览历史
        addToHistory();
    }
    
    /**
     * 创建模拟商品详情数据
     */
    private ProductDetail createMockProductDetail(int productId) {
        ProductDetail detail = new ProductDetail();
        detail.setId(productId);
        detail.setName("红富士苹果 新鲜水果 脆甜多汁");
        detail.setPrice(1.20);
        detail.setOriginalPrice(2.00);
        detail.setUnit("斤");
        detail.setSalesCount(410);
        detail.setImageUrl("https://images.pexels.com/photos/1132047/pexels-photo-1132047.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
        
        // 店铺信息
        detail.setShopId(1);
        detail.setShopName("山西农家乐果园");
        detail.setShopProductsCount(36);
        
        // 商品详情信息
        detail.setOrigin("山西临汾市尧都区");
        detail.setSpecification("精选5斤装、精选10斤装、普通10斤装");
        detail.setShelfLife("常温保存7-15天");
        detail.setFeatures("果肉细腻，汁多味甜，色泽鲜艳，营养丰富");
        
        // 详情图片
        List<String> detailImages = new ArrayList<>();
        detailImages.add("https://images.pexels.com/photos/1510392/pexels-photo-1510392.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
        detailImages.add("https://images.pexels.com/photos/1453713/pexels-photo-1453713.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
        detail.setDetailImages(detailImages);
        
        return detail;
    }
    
    /**
     * 显示商品详情
     */
    private void displayProductDetail() {
        // 显示商品图片
        Glide.with(this)
                .load(productDetail.getImageUrl())
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.placeholder_image)
                .into(binding.ivProduct);
        
        // 显示商品基本信息
        binding.tvProductName.setText(productDetail.getName());
        binding.tvPrice.setText("¥" + productDetail.getPrice());
        binding.tvOriginalPrice.setText("¥" + productDetail.getOriginalPrice());
        // 设置删除线
        binding.tvOriginalPrice.setPaintFlags(binding.tvOriginalPrice.getPaintFlags() | android.graphics.Paint.STRIKE_THRU_TEXT_FLAG);
        binding.tvSales.setText("销量: " + productDetail.getSalesCount() + "件");
        
        // 显示店铺信息
        binding.tvShopName.setText(productDetail.getShopName());
        
        // 显示商品参数
        binding.tvOrigin.setText(productDetail.getOrigin());
        binding.tvSpecification.setText(productDetail.getSpecification());
        binding.tvShelfLife.setText(productDetail.getShelfLife());
        binding.tvFeatures.setText(productDetail.getFeatures());
        
        // 显示详情图片
        displayDetailImages();
    }
    
    /**
     * 显示详情图片
     */
    private void displayDetailImages() {
        if (productDetail.getDetailImages() == null || productDetail.getDetailImages().isEmpty()) {
            return;
        }
        
        binding.detailImagesContainer.removeAllViews();
        
        for (String imageUrl : productDetail.getDetailImages()) {
            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    dpToPx(200));
            params.bottomMargin = dpToPx(8);
            imageView.setLayoutParams(params);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            
            Glide.with(this)
                    .load(imageUrl)
                    .placeholder(R.drawable.placeholder_image)
                    .error(R.drawable.placeholder_image)
                    .into(imageView);
            
            binding.detailImagesContainer.addView(imageView);
        }
    }
    
    /**
     * dp转px
     */
    private int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }
    
    /**
     * 检查是否已收藏
     */
    private void checkFavoriteStatus() {
        presenter.checkFavoriteStatus((int)productId, isFavorite -> {
            ProductDetailActivity.this.isFavorite = isFavorite;
            updateFavoriteButton();
        });
    }
    
    /**
     * 切换收藏状态
     */
    private void toggleFavorite() {
        if (isFavorite) {
            // 取消收藏
            presenter.removeFavorite((int)productId);
        } else {
            // 添加收藏
            Product product = convertToProduct();
            presenter.addFavorite(product);
        }
        
        isFavorite = !isFavorite;
        updateFavoriteButton();
    }
    
    /**
     * 更新收藏按钮状态
     */
    private void updateFavoriteButton() {
        int resId = isFavorite ? R.drawable.ic_favorite : R.drawable.ic_favorite_border;
        int colorId = isFavorite ? R.color.red_500 : R.color.black;
        
        binding.ivFavorite.setImageResource(resId);
        binding.ivFavorite.setColorFilter(ContextCompat.getColor(this, colorId));
    }
    
    /**
     * 加载购物车数量
     */
    private void loadCartCount() {
        presenter.loadCartItems();
    }
    
    /**
     * 添加到浏览历史
     */
    private void addToHistory() {
        Product product = convertToProduct();
        presenter.addHistory(product);
    }
    
    /**
     * 添加到购物车
     */
    private void addToCart() {
        Product product = convertToProduct();
        presenter.addToCart(product, 1);
        
        // 更新购物车数量
        cartCount++;
        updateCartBadge();
        
        Toast.makeText(this, "已添加到购物车", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 立即购买
     */
    private void buyNow() {
        final Product product = convertToProduct();
        Toast.makeText(this, "正在处理...", Toast.LENGTH_SHORT).show();
        
        // 添加日志输出
        Log.d("ProductDetailActivity", "buyNow: 商品ID=" + productId + 
              ", 转换后ID=" + product.getId() + 
              ", 名称=" + product.getName() + 
              ", 价格=" + product.getPrice());
        
        // 使用Presenter添加到购物车并立即购买
        presenter.addToCartAndBuy(product, 1, new UserDataContract.BuyCallback() {
            @Override
            public void onAddSuccess(int productId) {
                // 更新购物车数量
                cartCount++;
                updateCartBadge();
                
                // 添加日志输出
                Log.d("ProductDetailActivity", "onAddSuccess: 回调productId=" + productId);
                
                // 跳转到结算页面
                Intent intent = new Intent(ProductDetailActivity.this, CartActivity.class);
                intent.putExtra("direct_buy", true);
                intent.putExtra("product_id", productId);
                startActivity(intent);
                
                Toast.makeText(ProductDetailActivity.this, "正在进入结算...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAddFailed(String message) {
                Toast.makeText(ProductDetailActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    /**
     * 更新购物车徽章
     */
    private void updateCartBadge() {
        if (cartCount > 0) {
            binding.tvCartCount.setVisibility(View.VISIBLE);
            binding.tvCartCount.setText(String.valueOf(cartCount));
        } else {
            binding.tvCartCount.setVisibility(View.GONE);
        }
    }
    
    /**
     * 转换为Product对象
     */
    private Product convertToProduct() {
        Product product = new Product();
        
        // 添加日志输出
        Log.d("ProductDetailActivity", "convertToProduct: 原始商品ID=" + productDetail.getId());
              
        product.setId((int)productDetail.getId());
        product.setName(productDetail.getName());
        product.setPrice(productDetail.getPrice());
        product.setImageUrl(productDetail.getImageUrl());
        product.setUnit(productDetail.getUnit());
        product.setSellerId((int)productDetail.getShopId());
        
        // 添加日志输出
        Log.d("ProductDetailActivity", "convertToProduct: 转换后ID=" + product.getId() + 
              ", 名称=" + product.getName() + 
              ", 价格=" + product.getPrice());
              
        return product;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
    }

    // UserDataContract.View接口实现
    @Override
    public void showLoading() {
        // 不需要显示加载中
    }

    @Override
    public void hideLoading() {
        // 不需要隐藏加载中
    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showHistoryList(List<ProductHistory> historyList) {
        // 不需要显示历史列表
    }

    @Override
    public void showFavoriteList(List<Favorite> favoriteList) {
        // 不需要显示收藏列表
    }

    @Override
    public void showCartItems(List<CartItem> cartItems) {
        // 显示购物车数量
        cartCount = cartItems.size();
        updateCartBadge();
    }

    @Override
    public void showOrderList(List<Order> orderList) {
        // 不需要显示订单列表
    }

    @Override
    public void showEmptyView(int type) {
        // 不需要显示空视图
    }

    @Override
    public void showResult(boolean success, String message) {
        if (success) {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        } else {
            showError(message);
        }
    }
} 